package src.实验5;


import src.test5.RationalNumber;

import java.util.Stack;
import java.util.StringTokenizer;

public class Caculator {

    public String  getresult(String output)
    {
        Stack stack = new Stack();
        StringTokenizer st = new StringTokenizer(output);
        int numer = 1, denom = 1;
        String c,answer;

        RationalNumber r = new RationalNumber(numer, denom);
        while (st.hasMoreTokens()){
            c = st.nextToken();
            if (c.length() == 1) {
                if (c.compareTo("0") >= 0 && c.compareTo("9") <= 0) {
                    numer = Integer.parseInt(c);
                    r = new RationalNumber(numer, denom);
                    stack.push(r);
                } else {
                    RationalNumber m = (RationalNumber) stack.pop();
                    RationalNumber n = (RationalNumber) stack.pop();
                    if (c.compareTo("+") == 0) {
                        r = n.add(m);
                        stack.push(r);
                    }
                    if (c.compareTo("-") == 0) {
                        r = n.subtract(m);
                        stack.push(r);
                    }
                    if (c.compareTo("*") == 0) {
                        r = n.multiply(m);
                        stack.push(r);
                    }
                    if (c.compareTo("/") == 0) {
                        r = n.divide(m);
                        stack.push(r);
                    }
                }
            } else {
                numer = Integer.parseInt(String.valueOf(c.charAt(0)));
                denom = Integer.parseInt(String.valueOf(c.charAt(2)));
                r = new RationalNumber(numer, denom);
                stack.push(r);
                denom = 1;
            }
        }
        answer = stack.peek().toString();
        return answer;
    }
}